package com.inews.business.web;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import java.io.InputStream;
import java.io.OutputStream;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;


import com.inews.base.mapper.JsonMapper;


import com.inews.base.utils.InewsUtils;
import com.inews.base.vo.ExtData;

import com.inews.business.vo.BaiduResultVo;
import com.inews.business.vo.JinShanResultVo;
import com.inews.business.vo.KanboxVo;
import com.inews.business.vo.PanResultVo;
import com.inews.business.wangpan.baidu.BaiduPan;
import com.inews.business.wangpan.baidu.BaiduPanUtil;
import com.inews.business.wangpan.jinshan.KuaiPanUtil;
import com.inews.business.wangpan.sina.KanboxPan;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

	
	
	private String pareDate(String milltime){
		java.util.GregorianCalendar date=new GregorianCalendar();
		date.setTimeInMillis(Long.parseLong(milltime));
	return	DateFormatUtils.format(date, "yyyy-MM-dd hh:mm:ss");
		
	}
	
	
	/**
	 * 分页查询退休人员历史.
	 *
	 * @param request the request
	 * @param pageNumber the page number
	 * @param sort the sort
	 * @param vo the vo
	 * @return the object
	 * @throws Exception 
	 */
	@RequestMapping("findTeacherPage")
	@ResponseBody
	public Object findTeacherPage(ServletRequest request) throws Exception{
	
		ExtData<PanResultVo> extData = new 	ExtData<PanResultVo>();
		JinShanResultVo jinshanReslut=JsonMapper.nonEmptyMapper().JSONtoObject(KuaiPanUtil.metadata().get("t_result").toString(), JinShanResultVo.class);
		BaiduResultVo baiduResult=JsonMapper.nonEmptyMapper().JSONtoObject(BaiduPan.info(), BaiduResultVo.class);
		
		KanboxVo kanboxResult=JsonMapper.nonEmptyMapper().JSONtoObject(KanboxPan.info(), KanboxVo.class);
		List<PanResultVo> result=new ArrayList<PanResultVo>();
		for(int i=0;i<jinshanReslut.getFiles().size();i++){
			PanResultVo vo=new PanResultVo();
			vo.setFileName(jinshanReslut.getFiles().get(i).getName());
			vo.setFileSize(jinshanReslut.getFiles().get(i).getSize());
			vo.setModifyTime(jinshanReslut.getFiles().get(i).getModify_time());
			vo.setCreateTime(jinshanReslut.getFiles().get(i).getCreate_time());
			vo.setPanName("金山快盘");
			vo.setPanType("jinshan");
			result.add(vo);
			
		}
		
		
		for(int i=0;i<kanboxResult.getContents().size();i++){
			PanResultVo vo=new PanResultVo();
			vo.setFileName(kanboxResult.getContents().get(i).getFullPath());
			vo.setFileSize(kanboxResult.getContents().get(i).getFileSize());
			vo.setModifyTime(kanboxResult.getContents().get(i).getModificationDate());
			vo.setCreateTime(kanboxResult.getContents().get(i).getCreationDate());
			vo.setPanName("酷盘");
			vo.setPanType("kanbox");
			result.add(vo);
			
		}
		
		
		for(int i=0;i<baiduResult.getList().size();i++){
			PanResultVo vo=new PanResultVo();
			vo.setFileName(baiduResult.getList().get(i).getPath());
			vo.setFileSize(baiduResult.getList().get(i).getSize());
			vo.setModifyTime(pareDate(baiduResult.getList().get(i).getMtime()));
			vo.setCreateTime(pareDate(baiduResult.getList().get(i).getCtime()));
			vo.setPanName("百度云盘");
			vo.setPanType("baidu");
			result.add(vo);
			
		}
		
		extData.setRoot(result);
		extData.setSuccess(true);
		extData.setTotalProperty(Long.valueOf(result.size()));
		String json = JsonMapper.nonEmptyMapper().toJson(extData);
		return json;
	}
	
	
	

	
	
	

	
	/**
	 * 报表导出.
	 *
	 * @return the model and view
	 * @throws Exception 
	 */
	@RequestMapping("exportTeacherExcel")
	public ModelAndView  exportSalaryChangeExcel(HttpServletRequest req, HttpServletResponse res) throws Exception{
		  res.setContentType("text/html; charset=utf-8");
		  String panType=req.getParameter("panType");
		  String fileName = req.getParameter("fileName");
		  res.setContentType("application/octet-stream");
		  res.setHeader("Content-disposition", "attachment;filename="+ new String(fileName.getBytes(), "iso-8859-1"));//下载页一直在浏览器端乱码，转成iso-8859-1后问题解决，估计浏览器与服务端的默认编码为iso-8859-1（tomcat的默认编码也为iso-8859-1）
		  DataOutputStream dos = new DataOutputStream(res.getOutputStream());
    	//以流的方式读写文件
		 
		  
		  InputStream is = null;

		  BufferedInputStream reader = null;

		  try {
			  if(panType.equals("jinshan")){
				  Map<String,Object> result=KuaiPanUtil.download_file(fileName);
				   is = (InputStream)(result.get("_InputStream"));
			  }
			  else if(panType.equals("baidu")){
				  is=BaiduPan.download(fileName);
			  }
			  else if(panType.equals("kanbox")){
				  is=KanboxPan.download(fileName);
			  }
			 
		   reader = new BufferedInputStream(is);
		   byte[] content = new byte[40960];

		   int i = -1;
		   while ((i = reader.read(content)) != -1) {
		    dos.write(content, 0, i);
		   }
		   dos.flush();
		  } finally {
		   reader.close();
		   is.close();
		  }
		  return null;
	}
	
	
	
	
	
	/**
	 * 报表导入.
	 *
	 * @return the model and view
	 * @throws Exception 
	 */
	@RequestMapping(value="importExcel")
	@ResponseBody
	public ResponseEntity<String> importExcel(@RequestParam("excelFile") MultipartFile excelFile,String type) throws Exception{
		InputStream is=null;
		OutputStream out=null;
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.setContentType(MediaType.TEXT_HTML);
		try {
			is = excelFile.getInputStream();		
			File temp=File.createTempFile("_temp", "temp");
			out=new FileOutputStream(temp);
			byte[] buffer=new byte[1024];
			while(is.read(buffer)>0){
				out.write(buffer,0,buffer.length);
			}
			out.flush();  
			out.close();
			if(type.equals("jinshan")){
				KuaiPanUtil.upload_file(temp, excelFile.getOriginalFilename());	
			}
			else if(type.equals("baidu")){
				BaiduPan.UploadFile(temp, excelFile.getOriginalFilename());	
			}
			else if(type.equals("kanbox")){
				KanboxPan.UploadFile(temp, excelFile.getOriginalFilename());	
			}
			ExtData result=new ExtData();
			result.setSuccess(true);
			String json = JsonMapper.nonEmptyMapper().toJson(result);
			return new ResponseEntity<String>(json, responseHeaders, HttpStatus.OK);
		} catch (Exception e) {
			e.printStackTrace();
			ExtData result=new ExtData();
			result.setSuccess(false);
			result.setError(e.getMessage());
			String json = JsonMapper.nonEmptyMapper().toJson(result);			
			return new ResponseEntity<String>(json, responseHeaders, HttpStatus.EXPECTATION_FAILED);
			//throw new ExlImportException("导入失败");
		}
		finally{
			is.close();
			out.close();
		}
	}
	
	
	/**
	 * 删除退休人员信息.
	 *
	 * @param vo the vo
	 * @return the object
	 * @throws Exception 
	 */
	@RequestMapping("deleteTeacher")
	@ResponseBody
	public Object deleteTeacher(PanResultVo vo) throws Exception{
	//ExtData<TeacherVo> extData = service.deleteTeacher(vo, InewsUtils.getUserInfo());
			if(vo.getPanType().equals("kanbox")){
				KanboxPan.deleteFile(vo.getFileName());
			}
			else if(vo.getPanType().equals("baidu")){
				BaiduPan.deleteFile(vo.getFileName());
			}
			
			else if(vo.getPanType().equals("jinshan")){
				KuaiPanUtil.deleteFile(vo.getFileName());
			}
			
	ExtData result=new ExtData();
	result.setSuccess(true);
	String json = JsonMapper.nonEmptyMapper().toJson(result);
	return json;
	}
	

}
